﻿using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;

namespace Chemix.Util
{
    /// <summary>
    /// ChemixExporter is used to export data(time and mole mass) to csv files for analysis.
    /// </summary> 
    [RequireComponent(typeof(ChemixObject))]
    public class ChemixExporter : MonoBehaviour
    {
#if UNITY_EDITOR
        public class SubstanceData
        {
            public float lassMass = 0;
            public Substance substance = null;
        }

        // Use this for initialization
        void Start()
        {
            fileStream = new FileStream(m_FileName + ".csv", FileMode.OpenOrCreate, FileAccess.ReadWrite);
            fileStream.Close();
            fileStream = new FileStream(m_FileName + ".csv", FileMode.Truncate, FileAccess.ReadWrite);
            streamWriter = new StreamWriter(fileStream);
            m_ChemixObject = GetComponent<ChemixObject>();
        }

        void FixedUpdate()
        {
            string row = "";

            foreach (var co in m_ChemixObject.System.cobjects)
            {
                foreach (var s in co.Mixture.Substances)
                {
                    if (m_Formula2Mass.ContainsKey(s.formula))
                    {
                        continue;
                    }
                    else
                    {
                        var sd = new SubstanceData();
                        sd.substance = s;
                        m_Formula2Mass[s.formula] = sd;
                        m_Formulas.Add(s.formula);
                    }
                }
            }

            bool anyoneChanged = false;

            foreach (var formula in m_Formulas)
            {
                SubstanceData sd;
                if (m_Formula2Mass.TryGetValue(formula, out sd))
                {
                    if (sd.lassMass != sd.substance.mass)
                    {
                        anyoneChanged = true;
                        sd.lassMass = sd.substance.mass;
                    }
                    row += "," + sd.substance.mass;
                }
                else
                {
                    row += ",";
                }
            }

            if (anyoneChanged && row!="")
            {
                m_Data += Time.time + row + "\r\n";
            }
        }

        private void OnDestroy()
        {
            string firstRow = "time";
            foreach (var s in m_Formulas)
            {
                firstRow += "," + s;
            }
            m_Data = firstRow + "\r\n" +  m_Data;
            streamWriter.WriteLine(m_Data);
            streamWriter.Close();
            if (Chemix.ShouldLog(LogLevel.Message))
                Debug.Log("ChemixExporter: saved.");
        }

        [SerializeField]
        string m_FileName = "ChemixData";

        FileStream fileStream;
        StreamWriter streamWriter;
        ChemixObject m_ChemixObject;
        string m_Data;
        Dictionary<string, SubstanceData> m_Formula2Mass = new Dictionary<string, SubstanceData>();
        List<string> m_Formulas = new List<string>();
#endif
    }
}